﻿using System;
using System.Data;
using ComponentArt.Web.UI;
using Common;

namespace Common
{
    public static class Util
    {
        public static void BuildCategoryTree(TreeView tree)
        {
            var strSQL = string.Format("exec tblCategory_GetAllByCondition '{0}'", " AND CategoryId=346 OR CategoryId=356  AND status=1 ");
            var ds = DAL.GetDataSet(strSQL);

            var rootNode = CreateNode("--Lựa chọn danh mục--", "0", "../images/lines/folders.gif", true);
            tree.Nodes.Clear();
            tree.Nodes.Add(rootNode);

            foreach (DataRow dbRow in ds.Tables[0].Rows)
            {
                var newNode = CreateNode(dbRow["categoryName"].ToString(), dbRow["categoryId"].ToString(),
                                         "../images/lines/folders.gif", true);
                rootNode.Nodes.Add(newNode);
                var sql2 = string.Format("exec tblCategory_GetAllByCondition '{0}'",
                                         " AND parentId= " + Int32.Parse(dbRow["categoryId"].ToString()) +
                                         " AND status=1");
                var ds2 = DAL.GetDataSet(sql2);
                BuildSubTree(ds2.Tables[0], newNode);
            }

        }

        private static void BuildSubTree(DataTable dbTable, TreeViewNode node)
        {
            foreach (DataRow childRow in dbTable.Rows)
            {
                var childNode = CreateNode(childRow["categoryName"].ToString(),
                                           childRow["categoryId"].ToString(), "../images/lines/folder.gif",
                                           false);
                node.Nodes.Add(childNode);
                var sql3 = string.Format("exec tblCategory_GetAllByCondition '{0}'",
                                         " AND parentId= " + Int32.Parse(childRow["categoryId"].ToString()) +
                                         " AND status=1");
                var ds3 = DAL.GetDataSet(sql3);
                BuildSubTree(ds3.Tables[0], childNode);
            }
        }

        private static TreeViewNode CreateNode(string text, string value, string imageurl, bool expanded)
        {
            var node = new TreeViewNode {Text = text, Value = value, ImageUrl = imageurl, Expanded = expanded};
            return node;
        }
    }
}
